#include <iostream>
#include <string>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <cassert>
#define INDEX "./wwwroot"
template<class T>
class Protocol
{
public:
    Protocol() = default;
    void Cutrow(T& ret)
    {
        std::string request = ret;
        std::cout<< request <<std::endl;
        int pos = request.find("\r\n");
        if(pos == std::string::npos)
        {
            std::cout << "请求错误" << std::endl;
            //调用错误函数
            Eorron();
            return;
        }
        while(!request.empty())
        {
            pos = request.find("\r\n");
            if(pos == std::string::npos)
                break;
            request = request.substr(0, pos);
        }
        cutList(request);
    }
    void cutList(T& request)
    {
        int lpos = 0;
        int rpos = 0;
        while(!request.empty())
        {
            lpos = request.find(" ");
            rpos = request.rfind(" ");
            if(lpos == std::string::npos || rpos == std::string::npos)
                break;
            request = request.substr(lpos + 1, rpos + 1 - lpos - 2);
        }
        Findpath(request);
    }
    void Findpath(T& request)
    {
        assert(request.size() != 0);
        std::string path = INDEX;
        path += request;
        if(strcmp(path.c_str(), "./wwwroot/") == 0)
            path += "root.html";
        std::cout<<path<<std::endl;
        int fd = open(path.c_str(), O_RDONLY);
        if(fd < 0)
        {
            std::cout<<"所查找的路径不存在"<<std::endl;
            //调用错误函数
            Eorron();
            return;
        }
        char buffer[1024] = {'\0'};
        ssize_t s = 1024;
        while(s > 0)
        {
            s = read(fd, buffer, 1023);
            if(s > 0)
            {
                buffer[s] = '\0';
                _respon += buffer;
            }
        }
        close(fd);
        std::string respon = "HTTP/1.1 200 OK\r\n";
        respon += "Content-Type: text/html\r\n";
        respon += "\r\n";
        respon += _respon;
        _respon = respon;
    }
    void Eorron()
    {
        std::string respon = "HTTP/1.1 404 NotFound\r\n";
        respon += "Content-Type: text/html\r\n";
        respon += "\r\n";
        respon += "404NotFound";
        _respon = respon;
    }
    void Upda(T& ret)
    {
        ret = _respon;
    }
private:
    std::string _respon;
};